//连接websocket服务器
var ws = new WebSocket("ws://8.130.18.175:9501");
var db;

//连接成功事件
ws.onopen = function (evt) {
    console.log('connect success')
    let uid= localStorage.getItem('uid');
    if(uid){
        ws.send(JSON.stringify({uid:uid,type:"wsconnect"}));
    }

    //获取页面路径
    var pathname = window.location.pathname;
    console.log('路径:', pathname);

    //获取聊天记录
    if(pathname == '/index/chat/index'){
        ws.send(JSON.stringify({uid:uid,fuid:fuid,type:"getMsg"}));
    }

    // 定时发送ping
    setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
            // 发送ping帧
            let pingmsg = JSON.stringify({ type: 'ping' })
            ws.send(pingmsg); // 9是ping的opcode
        }
    }, 4000); // 每30秒发送一次ping
};

//收到服务器消息
ws.onmessage = function (evt) {
    var received_msg = evt.data;
    let callMsg = JSON.parse(received_msg);
    let calltype = callMsg.type;
    let data = JSON.parse(callMsg.data[0]);

    switch (calltype){
        //登录
        case 'loginCallback':
            let code = data.code;
            if(code == 1){
                localStorage.setItem('uid',data.uid);
                window.location.href = "http://8.130.18.175:9501/index/chat/userList";
            }else{
                alert(data.msg);
            }
            break;
        //用户信息回调
        case 'userCallback':
            uid = localStorage.getItem('uid');
            break;
        //消息
        case 'msgCallback':
            let calluser = data.username;
            let callmsg2 = data.msg;
            let str = '<p class="msg_de">'+calluser+'：'+callmsg2+'</p>';
            $("#msg_con").append(str);

            let dataMsg1 = {
                msg:callmsg2,
                uid:data.uid,
                username:data.username,
                ctime:data.ctime,
                roomid:0,
                relationid:data.uid+"-"+data.fuid,
            };
            let dataMsg2 = {
                msg:callmsg2,
                uid:data.uid,
                username:data.username,
                ctime:data.ctime,
                roomid:0,
                relationid:data.fuid+"-"+data.uid,
            };

            let request =  window.indexedDB.open('jhx',2);
            //数据库打开成功的回调
            request.onsuccess = function (event){
                db = event.target.result; //数据库对象
                addData(db,'chatMsgNew',dataMsg1);
                addData(db,'chatMsgNew',dataMsg2);
                db.close();
            }
            break;
        //获取会员列表
        case 'getUsersCallback':
            let userData = data.userData;
            let userDataArr = JSON.parse(userData);

            userDataArr.forEach(value => {
                console.log(value);
                let s = "<li class='user_li' onclick='uli("+value.id+")'>";
                s += value.username;
                if(value.isfriend != 1){
                    s += "<button class='addfriend' onclick='addfriend("+value.id+")'>加好友</button>";
                }
                s += "</li>";
                $("#fs").append(s)
            });
            break;
        //添加好友
        case 'addfriendCallback':
            if(data.code != 1){
                alert(data.msg);
            }else{
                alert(data.msg)
            }
            break;
        //获取消息列表
        case 'getMsgCallback':
            let messages = data.message;
            messages = JSON.parse(messages);
            console.log(messages);
            messages.forEach(function (value){
                $("#msg_con").append("<p>"+cursor.value.username+":"+cursor.value.msg+"</p>");
            })
            break;
    }
};

//连接关闭
ws.onclose = function () {
    // 关闭 websocket
    alert("连接已关闭...");
};